#include<mymuduo/TcpServer.h>
#include<string>
#include<iostream>
#include<mymuduo/Logger.h>
using namespace std;

class EchoServer
{
public:
    EchoServer(EventLoop *loop,
            const InetAddress &addr,
            const string &name)
            :server_(loop,addr,name)
            ,loop_(loop)
        {
            server_.setConnectionCallback(
              std::bind(&EchoServer::onConnnection,this,std::placeholders::_1) 
            );
            
            server_.setMessageCallback(
                std::bind(&EchoServer::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3)
            );

            server_.setThreadNum(3);

            
        }

        void start()
        {
            server_.start();
        }
private:

    // 建立连接或者断开的回调
    void onConnnection(const TcpConnectionPtr&conn)
    {
        if(conn->connected())
        {
            LOG_INFO("conn UP : %s",conn->peerAddress().toIpPort().c_str());
        }
        else
        {
             LOG_INFO("conn DOWN : %s",conn->peerAddress().toIpPort().c_str());
        
        }
    }

    // 可读写事件的回调
    void onMessage(const TcpConnectionPtr&conn,
                Buffer *buf,
                Timestamp time)
    {
        string msg = buf->retrieveAllAsString();
        conn->send(msg);
        conn->shutdown();
    }

    EventLoop *loop_;
    TcpServer server_;
};

int main()
{
    EventLoop loop;
    InetAddress addr(8000);
    EchoServer server(&loop,addr,"EchoServer-01");
    server.start();
    loop.loop(); // 启动mainloop的底层
    return 0;
}